package com.ming.seatMonitoring.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ming.seatMonitoring.pojo.DO.UserInfoDO;
import com.ming.seatMonitoring.pojo.entity.ResultBody;
import com.ming.seatMonitoring.service.LoginService;
import com.ming.seatMonitoring.util.JWTUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author 小明
 * @date 2021/10/19
 * @description
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Resource
    private LoginService loginService;

    @RequestMapping("/login")
    public ResultBody login(@RequestParam String userId,@RequestParam String passWord) {

        UserInfoDO login = loginService.login(userId,passWord);
        if (login!=null){
            HashMap<String, Object> map = new HashMap<>();
            try {
                //登录Service
                HashMap<String, String> payload = new HashMap<>();
                payload.put("userId",login.getUserId());
                payload.put("userName",login.getUserName());
                payload.put("email",login.getEmail());

                //生成JWT令牌
                String token = JWTUtil.getToken(payload);
                map.put("state",true);
                map.put("msg","认证成功");
                //响应token
                map.put("token",token);
            } catch (Exception e) {
                map.put("state",false);
                map.put("msg",e.getMessage());
            }
            System.out.println(map);
            return ResultBody.ok().data("token",map);
        }
        return ResultBody.error().message("登录失败，账号或密码错误!");
    }

    /**
     * 通过当前携带的token获取当前用户信息
     * @param request
     * @return
     */
    @RequestMapping("/explain")
    public ResultBody test(HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();
        //token=xx.xx.xx的头信息
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtil.verify(token);
        //通过k-v中的键取出（k不可以重复）
        String userId = verify.getClaim("userId").asString();
        String userName = verify.getClaim("userName").asString();
        String email = verify.getClaim("email").asString();
        System.out.println(userId);
        System.out.println(userName);
        System.out.println(email);

        map.put("userId",userId);
        map.put("userName",userName);
        map.put("email",email);

        return ResultBody.ok().data("info",map);
    }
}
